package org.tio.sitexxx.service.init;

import java.sql.Connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.utils.jfinal.P;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSourceFactory;

/**
 * @author tanyaowu
 * 2016年7月19日 下午5:23:21
 */
public class JFInit {

	private static Logger log = LoggerFactory.getLogger(JFInit.class);

	public static DruidPlugin[] druidPlugins;

	/**
	 * 有几个数据库
	 */
	public static int dbCount;

	/**
	 * 数据库名字
	 */
	public static String[] dbNames;

	/**
	 * Jfinal初始化加载
	 * 
	 */
	public static void init() {
		PropInit.init();

		dbNames = P.get("db.jdbc.multi.name").split(",");
		dbCount = dbNames.length;

		druidPlugins = new DruidPlugin[dbCount];

		//		druidPlugins = new DruidPlugin[dbCount];
		for (int i = 0; i < dbCount; i++) {//多数据源加载
			String dbName = dbNames[i];
			final String jdbcUrl = P.get(dbName + ".jdbc.url");
			final String jdbcUsername = P.get(dbName + ".jdbc.username");
			String jdbcPwd = P.get(dbName + ".jdbc.password"); //如果密码是加密存储的，在这里请解密一下
			final Integer jdbcPoolInitSize = P.getInt("db.jdbc.pool.initialSize");
			final Integer jdbcPoolMinIdle = P.getInt("db.jdbc.pool.minIdle");
			final Integer jdbcPoolMaxActive = P.getInt("db.jdbc.pool.maxActive");
			DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, jdbcUsername, jdbcPwd);
			druidPlugin = new DruidPlugin(jdbcUrl, jdbcUsername, jdbcPwd);
			druidPlugin.set(jdbcPoolInitSize, jdbcPoolMinIdle, jdbcPoolMaxActive);
			druidPlugin.setFilters("stat,wall");
			druidPlugin.start();
			druidPlugins[i] = druidPlugin;

			ActiveRecordPlugin arp = new ActiveRecordPlugin(dbName, druidPlugin);
			arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
			arp.getConfig().getDialect().setKeepByteAndShort(true);
			try {
				String[] xx = dbName.split("_");//[2];
				Class.forName("org.tio.sitexxx.service.model." + xx[xx.length - 1] + "._MappingKit").getMethod("mapping", ActiveRecordPlugin.class).invoke(null, arp);
			} catch (Exception e) {
				log.error("加载数据库映射关系错误");
			}

			arp.setShowSql(true);

			Engine engine = arp.getSqlKit().getEngine();
			engine.setBaseTemplatePath(null);
			engine.setSourceFactory(new ClassPathSourceFactory());
			arp.addSqlTemplate("sql/_all.sql");
			arp.start();
		}

	}

}
